//
//  Aop.m
//  Aop
//
//  Created by JYHeguang on 2023/11/22.
//

#import "Aop.h"
#import <Memery/Memery.h>

FOUNDATION_EXPORT StorageType const StorageAOP;
NSString * const StorageAOP = @"StorageAOP";

@interface Aop ()

@property (nonatomic, strong) id<IStorage> storage;
@end

@implementation Aop

+ (Aop *)shareInstance {
    static Aop *__shareInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        __shareInstance = [[Aop alloc] init];
    });
    return __shareInstance;
}

+ (nonnull id)instanceOf:(nonnull Protocol *)protocol {
    return [self.shareInstance instanceOf:protocol];
}

+ (void)registAop:(nonnull Class<IAop>)factory protocol:(nonnull Protocol *)protocol {
    [self.shareInstance registAop:factory protocol:protocol];
}

- (nonnull id)instanceOf:(nonnull Protocol *)protocol {
    NSString *protocolName = NSStringFromProtocol(protocol);
    Class<IAop> aop = [self.storage get:protocolName];

    id impl = [aop instance];
    return impl;
}

- (void)registAop:(nonnull Class<IAop>)factory protocol:(nonnull Protocol *)protocol {
    NSString *protocolName = NSStringFromProtocol(protocol);
    [self.storage create:factory key:protocolName];
}

- (id<IStorage>)storage{
    if (!_storage) {
        _storage = [Memery storageOf:StorageAOP];
    }
    return _storage;
}
@end
